'''公用方法'''

import hashlib
import random
from functools import wraps
from db.db_handler import MySQLHandler


def encrypt_data(data, salt=None):
    # 加密数据
    data_bin = data.encode('utf8')
    md5 = hashlib.md5()
    md5.update(data_bin)
    if not salt:
        encrypted_data = md5.hexdigest()
    else:
        encrypted_data = md5.hexdigest() + salt
    return encrypted_data


def generate_code(count: int):
    # 生成随机码
    code = ''
    code_list = [
        str(random.randint(0, 9)),
        chr(random.randint(65, 90)),
        chr(random.randint(97, 122))
    ]
    for i in range(count):
        temp_code = random.choice(code_list)
        code += temp_code
    return code


def login_input():
    username = input('请输入用户名:').strip()
    password = input('请输入密码:').strip()
    return username, password


def auth(roles):
    from interface import admin_iface, student_iface, teacher_iface
    def login_check(func):
        # 伪装装饰器
        @wraps(func)
        def inner(*args, **kwargs):
            if roles == 'admin' and admin_iface.login_dict_admin['role'] == '':
                print('【请先登录】')
                return False
            elif roles == 'student' and student_iface.login_dict_stu['role'] == '':
                print('【请先登录】')
                return False
            elif roles == 'teacher' and teacher_iface.login_dict_teacher['role'] == '':
                print('【请先登录】')
                return False
            res = func(*args, **kwargs)
            return res

        return inner

    return login_check


def show_schools():
    from db.db_handler import MySQLHandler
    mysql_obj = MySQLHandler()
    search_sql = 'select id,school_name,address from school'
    res = mysql_obj.search_all(sql=search_sql)
    if not res:
        return False, '【当前数据库中暂无数据，请联系管理员】'
    print('学校展示'.center(28, '='))
    for school_dict in res:
        print(f"【{school_dict['id']}】学校 : {school_dict['school_name']} 地址 : {school_dict['address']}")
    print('所有学校展示结束'.center(28, '='))
    return True, res


def show_courses(school_id):
    from db.db_handler import MySQLHandler
    mysql_obj = MySQLHandler()
    # search_school_sql = "select * from school where school_name = %(school_name)s"
    # school_dict = mysql_obj.search_one(search_school_sql, school_name=school_name)
    search_sql = "select id,course_name,course_desc from course where school_id = %(school_id)s"
    res = mysql_obj.search_all(sql=search_sql, school_id=school_id)
    if not res:
        return False, '【当前数据库中暂无数据，请联系管理员】'
    print(f' 课程展示 '.center(28, '='))
    for course_dict in res:
        print(f"【{course_dict['id']}】课程名称 : {course_dict['course_name']} 课程描述 : {course_dict['course_desc']}")
    print('所有课程展示结束'.center(28, '='))
    return True, res


def show_all_courses():
    mysql_obj = MySQLHandler()
    search_sql = "select * from course"
    course_dict_list = mysql_obj.search_all(sql=search_sql)
    print('展示课程'.center(30, '='))
    for course_dict in course_dict_list:
        print(
            f"课程名称【{course_dict['course_name']}】| 课程描述【{course_dict['course_desc']}】|学校ID【{course_dict['school_id']}】")
    print('展示结束'.center(30, '='))


def select_school():
    flag, school_list = show_schools()
    if not flag:
        return flag, school_list
    school_choice = input('请输入选择的学校编号:').strip()
    school_dict = {d['id']: d['school_name'] for d in school_list}
    if not school_choice.isdigit() or school_choice not in [str(i) for i in school_dict.keys()]:
        return False, '【编号有误！】'
    school_id = int(school_choice)
    return True, school_id


def select_course(school_id):
    flag, course_info = show_courses(school_id=school_id)
    if not flag:
        return flag, course_info
    course_choice = input('请输入课程编号:').strip()
    course_dict = {d['id']: d['course_name'] for d in course_info}
    if not course_choice.isdigit() or course_choice not in [str(i) for i in course_dict.keys()]:
        return False, '【编号有误】'
    course_id = int(course_choice)
    return True, course_id


def user_exists(username):
    mysql_obj = MySQLHandler()
    sql = 'select * from account where username=%(username)s'
    user_info = mysql_obj.search_one(sql, username=username)
    return user_info


def stu_username2stu_id(username):
    mysql_obj = MySQLHandler()
    search_sql = 'select id from student where name=%(name)s'
    res = mysql_obj.search_one(sql=search_sql, name=username)
    return res


def tch_username2tch_id(username):
    mysql_obj = MySQLHandler()
    search_sql = 'select id from teacher where name=%(name)s'
    res = mysql_obj.search_one(sql=search_sql, name=username)
    return res


def course_id2course_name(course_id):
    mysql_obj = MySQLHandler()
    search_sql = 'select course_name from course where id=%(course_id)s'
    res = mysql_obj.search_one(sql=search_sql, course_id=course_id)
    return res
